import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma } from '@/lib/db';

export async function GET(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    // 获取并等待参数
    const params = await context.params;
    
    // 检查是否有权限访问用户统计信息
    const requestingUserId = session.user.id;
    const userId = params.id;

    // 验证用户ID
    if (!userId) {
      return new NextResponse(
        JSON.stringify({ error: "缺少用户ID参数" }),
        { status: 400 }
      );
    }

    // 获取用户信息
    const user = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        name: true,
        email: true,
        image: true,
      },
    });

    if (!user) {
      return new NextResponse(
        JSON.stringify({ error: "找不到该用户" }),
        { status: 404 }
      );
    }

    // 获取用户任务完成情况
    const tasksData = await prisma.task.groupBy({
      by: ["status"],
      where: {
        assigneeId: userId,
      },
      _count: true,
    });

    // 获取用户项目参与情况
    const projectsCount = await prisma.projectUser.count({
      where: {
        userId: userId,
      },
    });

    // 获取近30天活动
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const recentActivity = await prisma.activity.findMany({
      where: {
        userId: userId,
        createdAt: {
          gte: thirtyDaysAgo,
        },
      },
      orderBy: {
        createdAt: "desc",
      },
      take: 10,
    });

    // 统计不同状态的任务数量
    const taskStats = {
      completed: 0,
      inProgress: 0,
      pending: 0,
      review: 0
    };

    tasksData.forEach((item) => {
      if (item.status === "DONE") {
        taskStats.completed = item._count;
      } else if (item.status === "IN_PROGRESS") {
        taskStats.inProgress = item._count;
      } else if (item.status === "TODO") {
        taskStats.pending = item._count;
      } else if (item.status === "REVIEW") {
        taskStats.review = item._count;
      }
    });

    // 返回统计结果
    return NextResponse.json({
      user,
      stats: {
        tasks: taskStats,
        projectsCount,
        recentActivity,
      },
    });
  } catch (error) {
    console.error("获取用户统计失败:", error);
    return new NextResponse(
      JSON.stringify({ error: "获取用户统计失败" }),
      { status: 500 }
    );
  }
} 